#!/bin/bash

set -e

[ "$(id -u)" = "0" ] ||
	{ echo "sorry, must be root"; exit 1; }

PT_TYPE="${PT_TYPE:-dos}" # dos or gpt
size=${DISK_SIZE_NEW:-1000M}
osize=${DISK_SIZE_ORIG:-500M}

MP=""
LODEV=""
TEMP_D=""

clearparts() {
	# read /proc/partitions, clearing any partitions on dev (/dev/loopX)
	local dev="$1"
	local short=${dev##*/} parts="" part=""
	parts=$(awk '$4 ~ m { sub(m,"",$4); print $4 }' \
		"m=${short}p" /proc/partitions)
	[ -z "$parts" ] && return
	echo "clearing parts [$parts] from $dev"
	for part in $parts; do
		echo "delpart $LODEV $part"
		delpart $LODEV $part
	done
	udevadm settle
}
cleanup() {
	if [ -n "$MP" ]; then
		echo "unmount $MP";
		umount "$MP";
		udevadm settle
	fi
	if [ -n "$LODEV" ]; then
		clearparts "$LODEV"
		echo "losetup --detach $LODEV";
		losetup --detach "$LODEV";
		udevadm settle
	fi
	[ ! -d "${TEMP_D}" ] || rm -Rf "${TEMP_D}"
}
rq() {
   local out="${TEMP_D}/out"
	"$@" > "$out" 2>&1 || { echo "FAILED:" "$@"; cat "$out"; return 1; }
}

TEMP_D=$(mktemp -d ${TMPDIR:-/tmp}/${0##*/}.XXXXXX)
trap cleanup EXIT

img="${TEMP_D}/disk.img"
mp="${TEMP_D}/mp"

echo "Partitioning $PT_TYPE orig_size=$osize grow_size=$size."
echo "growpart is $(which growpart)"
rm -f $img
[ ! -e $mp ] || rmdir $mp || { echo "failed rmdir $mp"; exit 1; }
mkdir $mp

truncate --size $osize "$img"

label_flag="--label=${PT_TYPE}"
echo "2048," | rq sfdisk $label_flag --force --unit=S "$img"

truncate --size "$size" "$img"

lodev=$(losetup --show --find "$img")
LODEV=$lodev
echo "set up $lodev"

# clear any old ones that might be around (LP: #1136781)
clearparts "$lodev"
partx --add $lodev
lodevpart="${lodev}p1"

rq mkfs.ext4 "${lodevpart}"

echo "mounting to $mp"
mount "${lodevpart}" "$mp"
MP="$mp"

echo "==== before ===="
grep "${lodev##*/}" /proc/partitions
sfdisk --list --unit=S "$lodev"

growpart -v -v "$lodev" 1

echo "==== after ===="
grep "${lodev##*/}" /proc/partitions

resize2fs "${lodevpart}"

echo == df ==
df -h "$mp"

# vi: ts=4 noexpandtab
